package com.doge.calcalbum.business.entry

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.doge.calcalbum.R
import com.doge.calcalbum.business.ITEM_CHECK
import com.doge.calcalbum.business.album.AlbumRepository
import com.doge.calcalbum.core.BaseActivity
import com.doge.calcalbum.core.PermissionUtil
import com.doge.calcalbum.core.base.adapters.ITEM_CLICKED
import com.doge.calcalbum.core.base.adapters.ITEM_LONG_CLICKED
import com.doge.calcalbum.databinding.ActivityEntryAsCoverBinding
import com.doge.calcalbum.db.model.Album
import com.doge.calcalbum.db.model.AlbumCover
import com.doge.calcalbum.db.model.Entry
import com.doge.calcalbum.utils.*
import com.doge.calcalbum.widgets.GridItemDecoration

/***
 * pick new image set as album cover
 */
class EntryAsCoverActivity : BaseActivity() {
    private val binding by lazy { ActivityEntryAsCoverBinding.inflate(layoutInflater) }
    private val albumId by lazy { intent.getIntExtra(EXTRA_ALBUM_ID, Album.DEFAULT_PICTURE_ID) }
    private val viewModel by viewModels<EntryViewModel> { EntryViewModelFactory(albumId) }
    private val adapter by lazy { EntryAdapter() }
    private var hasUploaded = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        systemWindowInsetsTop.observe(this) {
            binding.fitsSys.setPadding(it / 2)
        }
        binding.pageBack.setOnClickCallback { finish() }
        binding.setCover.setOnClickCallback { setCover() }
        binding.recyclerView.itemAnimator = null
        val itemDecoration = object : GridItemDecoration(2.dp, Color.TRANSPARENT) {
            override fun getItemSidesIsHaveOffsets(itemPosition: Int) =
                arrayOf(itemPosition % 4 != 0, true, itemPosition % 4 != 3, true)
        }
        binding.recyclerView.addItemDecoration(itemDecoration)
        binding.recyclerView.layoutManager = GridLayoutManager(binding.recyclerView.context, 4)
        binding.recyclerView.adapter = adapter
        adapter.enterEdit()
        adapter.setListener(::handleAdapterCallback)
        viewModel.album.observe(this) {
            binding.pageTitle.text = it?.title
        }
        viewModel.entryList.observe(this) {
            binding.empty.isVisible = it.isNullOrEmpty()
            adapter.submitList(it)
        }
    }

    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            ITEM_CLICKED, ITEM_LONG_CLICKED, ITEM_CHECK -> {
                adapter.clearSelected()
                adapter.switch(item as? Entry?)
            }
        }
    }


    private fun setCover() {
        if (hasUploaded) return
        hasUploaded = true
        val selected = adapter.selected
        if (selected.isEmpty()) {
            toast(R.string.please_select_entry)
        } else {
            AlbumRepository.get().updateCover(AlbumCover(albumId, selected.first().id))
            Activities.finish(EntryAsCoverActivity::class.java)
        }
    }

    companion object {
        private const val EXTRA_ALBUM_ID = "albumId"
        fun start(context: FragmentActivity?, albumId: Int?) {
            if (context == null || albumId == null) return

            PermissionUtil.requestPermissions(context.lifecycle, android.Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE) {
                if (it) {
                    context.startActivity(Intent(context, EntryAsCoverActivity::class.java).apply {
                        putExtra(EXTRA_ALBUM_ID, albumId)
                    })
                }
            }
        }
    }
}